library(ggplot2)
# 1.
# 读取文件进入R环境
count <- read.table("D:\\RLocal\\Class3\\Rshijian3\\RNAseq_Data\\count.csv",header = TRUE,row.names = 1)

# 读取特定行为向量
enf_row <- count["ENSG00000000003", ]
enf_row2 <- count["ENSG00000000005", ]
par(mfrow = c(2, 2))

# 开始画图
hist1 <- hist(as.numeric(enf_row), main = "ENSG-3频数统计图", xlab = "Value", col = "steelblue", breaks = 50, xlim = c(0, max(as.numeric(enf_row))))
# 找出非0的柱子索引
nonzero_index <- which(hist1$counts > 0)
# 标注频数
text(x = hist1$mids[nonzero_index],
     y = hist1$counts[nonzero_index],
     labels = hist1$counts[nonzero_index],
     pos = 3,   # 标签放在柱子上方
     cex = 0.5, # 字体大小
     col = "black")

hist2 <- hist(as.numeric(enf_row2), main = "ENSG-5频数统计图", xlab = "Value", col = "steelblue", breaks = 50, xlim = c(0, max(as.numeric(enf_row2))))
nonzero_index2 <- which(hist2$counts > 0)
text(x = hist2$mids[nonzero_index2],
     y = hist2$counts[nonzero_index2],
     labels = hist2$counts[nonzero_index2],
     pos = 3,   # 标签放在柱子上方
     cex = 0.5, # 字体大小
     col = "black")


# 2.
# 读取文件进入R环境
count2 <- read.csv("D:\\RLocal\\Class3\\Rshijian3\\ADdata\\final_merged_data.csv",header = TRUE,row.names = 1)
# 发现对数绘图效果更好
count2p <- log1p(count2)
# 转置矩阵，使得看得更加清
count2t <- t(count2p)
# 计算矩阵
distance_matrix <- dist(count2t)
# 绘制树状图
hc <- hclust(distance_matrix, method = "single")
# 画图，规定画板
par(mfrow = c(1,1))
plot(hc,main = "ADData聚类树状图",cex.axis=0.5,cex.main=1.2, cex=0.5,hang=-1)


# 3.
# 加载RData文件
load("D:\\RLocal\\Class4\\volcano.RData")
# 设置阈值
log2FC_threshold <- log2(1.2)
p_threshold <- 0.05

# 创建分类列
prostat$group <- "无显著差异"
prostat$group[prostat$P < p_threshold & prostat$FC > log2FC_threshold] <- "上调"
prostat$group[prostat$P < p_threshold & prostat$FC < -log2FC_threshold] <- "下调"

# 添加 -log10(P) 列
prostat$logP <- -log10(prostat$P)

# 开始绘图并保存为JPG
ggplot(prostat, aes(x = FC, y = logP, color = group)) +
  geom_point(alpha = 0.8, size = 2) +
  scale_color_manual(values = c("上调" = "red", "下调" = "blue", "无显著差异" = "gray")) +
  geom_vline(xintercept = c(-log2FC_threshold, log2FC_threshold), linetype = "dashed", color = "black") +
  geom_hline(yintercept = -log10(p_threshold), linetype = "dashed", color = "black") +
  labs(title = "Volcano Plot",
       x = "log2 Fold Change",
       y = "-log10(P value)",
       color = "Regulation") +
  theme_minimal()

# 保存为 JPG 文件
ggsave("volcano_plot_ggplot.jpg", width = 8, height = 6, dpi = 300)